package com.xgq.drink.utils;

import com.xgq.drink.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
public class RedisUtil {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplateObject;

    private static final String USER_ROLES_KEY_PREFIX = "user:roles:";
    private static final long USER_ROLES_EXPIRE_TIME = 24 * 60 * 60; // 24小时

    public void setTokenBlacklist(String token, long expirationMillis) {
        if (expirationMillis <= 0) {
            expirationMillis = 5 * 60 * 1000; // 默认5分钟
        }
        redisTemplate.opsForValue().set(
                token,
                "blacklisted",
                expirationMillis,
                TimeUnit.MILLISECONDS
        );
    }

    public void set(String key, String value, long timeout, TimeUnit timeUnit) {
        if (value == null) {
            // 如果 value 为 null，设置一个短暂的过期时间来清除缓存
            redisTemplate.opsForValue().set(key, "", 1, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
        }
    }

    public String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public boolean isTokenBlacklisted(String token) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(token));
    }

    public void setPermissionsByUserId(String userId, String permissions) {
        String key = "permission:" + userId;
        redisTemplate.opsForValue().set(key, permissions);
    }

    public String getPermissionsByUserId(String userId) {
        String key = "permission:" + userId;
        return redisTemplate.opsForValue().get(key);
    }

    // 检查Token是否在黑名单中
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    public void setUserRoles(String userId, List<Role> roles) {
        try {
            if (userId == null || userId.isEmpty()) {
                System.out.println("Error: userId is null or empty");
                throw new IllegalArgumentException("userId cannot be null or empty");
            }
            
            if (roles == null) {
                System.out.println("Error: roles list is null");
                throw new IllegalArgumentException("roles cannot be null");
            }
            
            System.out.println("Saving roles to Redis for user: " + userId);
            System.out.println("Roles to save: " + roles);
            
            String key = USER_ROLES_KEY_PREFIX + userId;
            // 将角色列表转换为字符串列表
            List<String> roleStrings = roles.stream()
                    .map(Role::toString)
                    .toList();
            // 使用StringRedisTemplate存储角色信息
            redisTemplate.opsForValue().set(key, String.join("|", roleStrings), USER_ROLES_EXPIRE_TIME, TimeUnit.SECONDS);
            
            System.out.println("Successfully saved roles to Redis");
            
            // Verify the save operation
            String savedValue = redisTemplate.opsForValue().get(key);
            System.out.println("Verification - Retrieved value: " + savedValue);
        } catch (Exception e) {
            System.out.println("Redis Error in setUserRoles: " + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("Failed to save user roles to Redis: " + e.getMessage(), e);
        }
    }

    public List<Role> getUserRoles(String userId) {
        String key = USER_ROLES_KEY_PREFIX + userId;
        String value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            // 使用 lambda 表达式代替方法引用
            return Arrays.stream(value.split("\\|"))
                    .map(str -> {
                        if (str == null || str.isEmpty()) {
                            return null;
                        }
                        String[] parts = str.split(":");
                        if (parts.length != 4) {
                            return null;
                        }
                        Role role = new Role();
                        try {
                            role.setId(Long.parseLong(parts[0]));
                            role.setName(parts[1]);
                            role.setCode(parts[2]);
                            role.setStatus(Integer.parseInt(parts[3]));
                            return role;
                        } catch (NumberFormatException e) {
                            System.out.println("Error parsing role from string: " + str);
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        return null;
    }

    public void removeUserRoles(String userId) {
        String key = USER_ROLES_KEY_PREFIX + userId;
        redisTemplateObject.delete(key);
    }
    // RedisUtil中需要存在的方法
    public void hset(String key, String field, String value) {
        redisTemplate.opsForHash().put(key, field, value);
    }

    public void hdel(String key, String field) {
        redisTemplate.opsForHash().delete(key, field);
    }
}